package org.gaaidou.ptarmigan.springboot.core.common;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.gaaidou.ptarmigan.springboot.core.serialize.json.JsonUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public final class ServletUtil {


    private static final String UNKNOWN = "unknown";


    public static HttpServletRequest getReq() {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }


    public static HttpServletResponse getResp() {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        return ((ServletRequestAttributes) requestAttributes).getResponse();
    }

    public static  void respJson(HttpServletResponse response, Object data, HttpStatus httpStatus) {
        PrintWriter out = null;
        try {
            response.setContentType(MediaType.APPLICATION_JSON_UTF8.toString());
            response.setStatus(httpStatus.value());
            out = response.getWriter();
            out.write(JsonUtil.toJsonString(data));
        } catch (IOException e) {
            log.error("Occur exception from responding json, exception: {}" ,e.getMessage(), e);
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }

    public static String getIpAddress() {
        final HttpServletRequest request = getReq();
        String ip = request.getHeader("x-forwarded-for");

        if (!StringUtils.isEmpty(ip)) {
            ip = ip.split(",")[0].trim();
        }

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
